
window.onload=function(){

	var numberOfMemorize = 10;

  	//initialize stack
  	var patty_stack= new Array();
  	var word_stack = new Array();
  	var hint_stack= new Array();
  	var kenny_stack = new Array();
  	var patty, word;

	var canvas= document.getElementById("game"),
		stage= new Stage (canvas);
		stage.mouseEventsEnabled = true;
		//stage.enableMouseOver();

	// static bg objects variables
	var bg, table, overlay, plate, bun_bottom, bun_top,
		body, leftArm, rightArm, eyes, faceShadow, mouth, face, dialog, feedEricButton, hint;

	//containers
	var setup, burger, eric, eric2, allKennyContainer;
	// script array
	var script_cnt=0;
	var instr_cnt=0;
	
	var script= new Array(
		"What happened to me? \n I am starving!! ",
		" Hey you! \n Make me an epic burger \n with ingredients below!",
		" Each ingredient is \n represented by a \n keyboard key.",
		"Now, press the keys on \n your keyboard to make \n the most epic burger! \n Remember variety counts!"
	);
	
	var gameScript= new Array(
		"Now go memorize your\n recipe and serve \n your kick ass burger \n to Kenny 10 times.",
		"What...? Too many?",
		"Shut up! Just \n respect my authority!",
		"Do it as fast as you can... \n Get set and GO!"
	);
	//singleton game controller object
	function GameController() 
	{
		if ( arguments.callee._singletonInstance )
			return arguments.callee._singletonInstance;
		arguments.callee._singletonInstance = this;
		this.passwordCreated = false;
		this.password = "";
		this.numberOfServedCustomer = 0;
		this.currentIndex = 0;
  	}

	init();

	function init(){
		setup= new Container();
		eric= new Container();
		eric2 = new Container();

		burger= new Container();
		wordStackContainer = new Container();
		
		bg= new Bitmap("./img/background.png");
		table= new Bitmap("./img/table.png");
		table.x=0; table.y=450; table.alpha=0.85;

		plate= new Bitmap("./img/plate.png");
		plate.x=30; plate.y=410; plate.alpha=0.85;


		bun_bottom= new Bitmap("./img/bun_bottom.png");
		bun_bottom.x=50; bun_bottom.y=400;

		bun_top= new Bitmap("./img/bun_top.png");
		bun_top.x=45; bun_top.y=325;

		plate= new Bitmap("./img/plate.png");
		plate.x=30; plate.y=410; plate.alpha=0.85;

		rightArm= new Bitmap("./img/cartman/bodies/rightArm.png");
		rightArm.x=780; rightArm.y=120;

		leftArm= new Bitmap("./img/cartman/bodies/leftArm.png");
		leftArm.x=690; leftArm.y=120;
		leftArm.regX= leftArm.width/2;leftArm.regY= leftArm.height/2;


		body= new Bitmap("./img/cartman/bodies/fatbody1.png");
		body.x=745; body.y=115;
		body.scaleX=0.5;
		body.regX = 83/2; body.regy = 102/2;

		face= new Bitmap("./img/cartman/faces/skinnyFace.png");
		face.x=700; face.y=10;
		//head.regX= 144/2;head.regY= 124/2;
		
				
		faceShadow= new Bitmap("./img/cartman/faces/shadow.png");
		faceShadow.x=720; faceShadow.y=60;
		
		eyes= new Bitmap("./img/cartman/eyes/sadEyes.png");
		eyes.x=725; eyes.y=40;

		mouth= new Bitmap("./img/cartman/mouths/sad_smile.png");
		mouth.x=745; mouth.y=100;
		
		dialog= new Bitmap("./img/dialog.png");
		dialog.x=400; dialog.y=10;

		speech= new Text (script[script_cnt], "bold 20px Arial");
		script_cnt++;
		// speech.textAlign="center";
		speech.color="#343232";
		//style text
		speech.x= 410;
		speech.y=15;
		
		recipe= new Text ("Recipe: ","bold 20px Arial");
		recipe.color="#000";
		//style texts
		recipe.x= 120;
		recipe.y=470;
		

		feedEricButton= new Bitmap ("./img/button1.png");
		feedEricButton.x=100; feedEricButton.y=540;
		feedEricButton.onClick = feedEric;

		continueB= new Bitmap ("./img/nextB.png");
		continueB.x=585; continueB.y=120;
		continueB.onClick = continueDialog;
		
		gameContinueB= new Bitmap ("./img/nextB.png");
		gameContinueB.x=585; gameContinueB.y=120;
		gameContinueB.visible=0;
		
		keyboard = new Bitmap ("./img/keyboard.png");
		keyboard.x = 350; keyboard.y = 200;
		
		

		setup.addChild(bg);
		setup.addChild(table);
		setup.addChild(plate);
		burger.addChild(bun_top);
		burger.addChild(bun_bottom);
		
/* 		eric.addChild(leg); */
		eric.addChild(body);
		eric.addChild(leftArm);
		eric.addChild(rightArm);
		eric.addChild(face);
		eric.addChild(dialog);
		eric.addChild(speech);
		eric.addChild(continueB);
		eric.addChild(gameContinueB);
		eric.addChild(faceShadow);
		
		eric.addChild(eyes);
		eric.addChild(mouth);

		setup.addChild(feedEricButton);
		setup.addChild(recipe);
		setup.addChild(keyboard);


		overlay= new Shape();
 		overlay.graphics.beginFill(Graphics.getRGB(0,0,0));
		overlay.graphics.rect(0,0,850,600);
		overlay.alpha=0.8;

		stage.addChild(setup);
		stage.addChild(burger);
		stage.addChild(overlay);
		stage.addChild(eric);

		stage.update();


		face.image.width *0.5;
		face.image.height *0.5;
		Ticker.setFPS (60);
		Ticker.addListener(stage);
		//var leftTween = new Tween.get(leftArm).to({rotation:+10}, 1000);
		//var rightTween = new Tween.get(rightArm).to({rotation:-20}, 1000);
		// var headTween = new Tween.get(head).to({rotation:-20}, 1000);

		//create game controller to keep track of game states
		GameController();
		
		//initKenny();
			
	}
	
	function initKenny()
	{
		kenny_stack = new Array();
		allKennyContainer = new Container();
		allKennyContainer.x = 800; allKennyContainer.y = 350;
		
		for (var i=0;i<numberOfMemorize;i++)
		{
			var kennyHead = new Bitmap("./img/kennyHead.png");
			kennyHead.x = 0; kennyHead.y = 0;
			//kennyHead.scaleX = 0.5; kennyHead.scaleY = 0.5;
			
			var kennyBody = new Bitmap("./img/kennyBody.png");
			kennyBody.x = 0; kennyBody.y = 7;
			//kennyBody.scaleX = 0.5; kennyBody.scaleY = 0.5;
			
			var kennyContainer = new Container();
			kennyContainer.x = 75*i;
			kennyContainer.y = 0;
			kennyContainer.scaleX = 0.5; kennyContainer.scaleY = 0.5;
			
			kennyContainer.addChild(kennyHead);
			kennyContainer.addChild(kennyBody);
			
			allKennyContainer.addChild(kennyContainer);
		}
		
		stage.addChild(allKennyContainer);
		var myTween = Tween.get(allKennyContainer).to({x:300},5000,Ease.linear).call();
		
		stage.update();
	}

	function tick(){
		//any animation

		head.rotation+=2; 
		stage.update();
		
	}
	
/********************* Entropy Functions ***************************/
function calculateAlphabetSize(password) {
		var alphabet = 0, lower = false, upper = false, numbers = false, symbols1 = false, symbols2 = false, other = '', c;
		
		for(var i = 0; i < password.length; i++) {
			c = password[i];
			if(!lower && 'abcdefghijklmnopqrstuvwxyz'.indexOf(c) >= 0) {
				alphabet += 26;
				lower = true;
			}
			else if(!upper && 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(c) >= 0) {
				alphabet += 26;
				upper = true;
			}
			else if(!numbers && '0123456789'.indexOf(c) >= 0) {
				alphabet += 10;
				numbers = true;
			}
			else if(!symbols1 && '!@#$%^&*()'.indexOf(c) >= 0) {
				alphabet += 10;
				symbols1 = true;
			}
			else if(!symbols2 && '~`-_=+[]{}\\|;:\'",.<>?/'.indexOf(c) >= 0) {
				alphabet += 22;
				symbols2 = true;
			}
			else if(other.indexOf(c) === -1) {
				alphabet += 1;
				other += c;
			}
		}
		
		return alphabet;
	}
	
	function calculateEntropy(password) {
		if(password.length === 0) return 0;
		var entropy = password.length * Math.log(calculateAlphabetSize(password)) / Math.log(2);
		return (Math.round(entropy * 100) / 100) + ' bits';
	}

/*********************** Event Handlers ******************************/
  function continueInstruction (e){
  	if (instr_cnt==(gameScript.length)){
  		//game start
  		overlay.visible=0;
  		gameContinueB.visible=0;
  		instr_cnt=0;
  		initKenny();
/*
  		for (var i=0;i<hint_stack.length;i++){
	  		hint_stack[i].x=400+20*i;
	  		hint_stack[i].y=300;
	  		stage.addChild(hint_stack[i]);
  		}
*/
  		
  		
  		stage.update();
  	}else if(instr_cnt==(gameScript.length-1)){
  		gameContinueB.image.src= ("./img/Start.png");
  		gameContinueB.y-=0;gameContinueB.x+=0;
  		speech.text= gameScript[instr_cnt++];
	  	stage.update();
  	}else{
  		//change text
	  	speech.text= gameScript[instr_cnt++];
	  	stage.update();

  	}
  	
  }


  function continueDialog (e){
  	if (script_cnt==(script.length)){
  		//game start
  		overlay.visible=0;
  		continueB.visible=0;
  		script_cnt=0;
  		$(document).keydown(detectBackspace);
  		$(document).keypress(detectKey);
  		leftTween.play();
  		stage.update();
  	}else if(script_cnt==(script.length-1)){
  		continueB.image.src= ("./img/Start.png");
  		continueB.y-=0;continueB.x+=0;
  		speech.text= script[script_cnt++];
	  	stage.update();
  	}else{
  		//change text
	  	speech.text= script[script_cnt++];
	  	stage.update();

  	}
  	
  }

  function feedEric(e){
	  
	//check for lame burger
	if (word_stack.length > 5)
	{
		//save created password to gamecontroller
	  	for (var i=0;i<word_stack.length;i++)
	  	{
	  		GameController().password = GameController().password.concat(word_stack[i].text);
	  	}
	  	GameController().passwordCreated = true;
	  	
	  	
	  	//reset variable
	  	feedEricButton.visible = 0;
	  	keyboard.visible=0;
		GameController().currentIndex = 0;
		
		// make hint stack text
		hint = new Text ("HINT: ","bold 20px Arial");
		hint.x= 400; hint.y=180;
		stage.addChild(hint);
		for (var i=0;i<GameController().password.length;i++){
			var temp= new Text(GameController().password.charAt(i),"bold 20px Arial");
			hint_stack.push(temp);
			var temp_x= 400+i*30;
			hint_stack[i].x= temp_x; hint_stack[i].y=200;
			stage.addChild(hint_stack[i]);
		}
				
		
		//make overlay
		overlay.visible=1;
		gameContinueB.visible=1;
		$(document).keydown();
  		$(document).keypress();
  		gameContinueB.onClick = continueInstruction;
  		speech.text=gameScript[0]; instr_cnt++;
		
		memorizeReset();
		
		stage.update();
		
	  	console.log(GameController().password);
	}
	else
	{
		speech.text = "Are you kiddin'? \n This is like the smallest \n burger ever. \n Gimme MORE!";
	}
}

  function addPatty(keyID){
	    // stack.push(keyID);
	    var input= String.fromCharCode(keyID);
	    bun_top.y-=20;
	if (!GameController().passwordCreated)
	   	{
	    var src_str= './img/patties/'+keyID+'.png';
	    
	    patty= new Bitmap(src_str);
	    //update top bun height
	    
	
	    //draw patty
	    patty.x=25; patty.y=bun_top.y+60;
	   	burger.addChild(patty);
	
	   	//draw word
   	
	   	word= new Text(input, "bold 18px Arial");
	   	word.x=20+15*(GameController().currentIndex+1); word.y=500;
	   	stage.addChild(word);
   	}
   	else
   	{
	   	word_stack[GameController().currentIndex].visible = 1;
	   	patty_stack[GameController().currentIndex].visible = 1;
   	}

   	// change body/dialog

	stage.update();
	
	if (!GameController().passwordCreated)
	{
		patty_stack.push(patty);
		word_stack.push(word);
	}
	
    //update counter for index
    GameController().currentIndex ++;
	console.log ("patty size: "+patty_stack.length);
	//word_stack.push(word);
  }

  function removePatty(){
    
  	// alert(stack.length-1);
    //remove patty
    if (patty_stack.length>=1)
    {
    	patty_stack[patty_stack.length-1].visible=0;
    	word_stack[word_stack.length-1].visible=0;
    	burger.removeChild(patty);
    	bun_top.y+=20;
   		stage.update();
   		patty_stack.pop();
   		word_stack.pop();
   		console.log ("patty size: "+patty_stack.length);
   		
   		//lower the index number
   		GameController().currentIndex--;
   		//slim down

    }
  }

  function detectBackspace(e){

    if (e.keyCode==8 && !GameController().passwordCreated && patty_stack.length > 0){
      e.preventDefault();
      removePatty();
      sizeDownEric();
    }
  }
  
  function memorizeReset()
  {
	//reset burger height
	bun_top.y = 325;
	
	//reset text and patty on screen
	
	var temp = word_stack.length;
	for (var i=0;i<word_stack.length;i++)
	{
		word_stack[i].visible = 0;
		patty_stack[i].visible = 0;
	}
	
	//reset index counter
	GameController().currentIndex = 0;
					
  }
  
  function updateKenny()
  {
	  for (var i=0;i<GameController().numberOfServedCustomer;i++)
	  {
		  var kennyContainer = allKennyContainer.getChildAt(i);
		  kennyContainer.visible = 0;
	  }
	  var myTween = Tween.get(allKennyContainer).to({x:250-kennyContainer.x},200,Ease.linear).call();
	  stage.update();
  }
  
  function sizeUpEric()
  {

  	  if (word_stack.length== 6){
  	  	  faceShadow.visible=0;
  	  	  face.image.src=("./img/cartman/faces/fatFace.png");
  	  	  eyes.image.src= ("./img/cartman/eyes/normalEyes.psd");
  	  	  mouth.image.src= ("./img/cartman/mouths/smile.png");
  	  	  eyes.x+=20;
  	  	  mouth.x+=20;
  	  }
  	  else if (word_stack.length== 4){
  	  	  faceShadow.visible=0;
  	  	  mouth.image.src= ("./img/cartman/mouths/smile1.psd");
  	  }
  	  
	  body.scaleX = body.scaleX+0.05;
	  rightArm.x+=0.03*160;
	  stage.update();
  }
  
  function sizeDownEric()
  {

  	  if (word_stack.length== 5){
	  	  face.image.src=("./img/cartman/faces/skinnyFace.png");
	  	  eyes.x-=20; 
  	  	  mouth.x-=20;
  	  }else if (word_stack.length== 3){
  	  	  faceShadow.visible=1;
  	  	  eyes.image.src= ("./img/cartman/eyes/sadEyes.png");
  	  	  mouth.image.src= ("./img/cartman/mouths/sad_smile.png");
  	  }


  	  body.scaleX = body.scaleX-0.05;
	  rightArm.x-=0.03*160;
	  stage.update();
  }
  
  function showHint(level)
  {
      //clear chars up to the level
      
  	  if (level <= GameController().password.length)
  	  {
		  for (var i=0;i<level;i++)
		  {
			  word_stack[i].visible = 0;
		  }
	  }
	  
	  //if the password is longer than 10 characters then on the last memorization make the whole hint disappear
	  if (GameController().password.length > numberOfMemorize && GameController().numberOfServedCustomer > 8)
	  {
		  for (var i=0;i<GameController().password.length;i++)
		  {
			  word_stack[i].visible = 0;
		  }
	  }
  }
  
  function showCompleteScreen()
  {
  		//calculate entropy
  		var entropy = calculateEntropy(GameController().password);
  		
		//memorize completed move to congrduate user
		eric.visible=0;
		table.visible=0;
		plate.visible=0;
		recipe.visible=0;
		hint.visible=0;
		//animate burger to center
		
		
		var winText= new Bitmap ("./img/finalScreen/congrats.png");
		winText.x= 200;
		winText.y=0;
		burger.x+=100;burger.y+=50;
		for (var i=0;i<word_stack.length;i++)
		{
		//word_stack[i].x+=300;word_stack[i].y-=100;
		word_stack[i].visible=0;
		}
		
		bg.image.src= ("./img/finalScreen/bg.jpg");	
		var nutritionText= new Bitmap("./img/finalScreen/quotes.png"); 
		nutritionText.x= 350;
		nutritionText.y=0;
		var questionText= new Bitmap("./img/finalScreen/question.png");
		questionText.x= 20;
		questionText.y=480;
		
		var yesB= new Bitmap("./img/finalScreen/yes.png");
		yesB.onClick= function(){
		alert("This study is finished. Please go talk to the moderator.Thank you!")
		};
		yesB.x= 450;
		yesB.y=480;
		
		var noB= new Bitmap("./img/finalScreen/no.png");
		noB.x= 650;
		noB.y=480;
		noB.onClick= function(){
		alert("This study is finished! Please go talk to the moderator!")
		};
		
		//remove hint
		for (var i=0;i<hint_stack.length;i++)
		{
			hint_stack[i].visible=0;
				            	
		}
		
		var entropyString = "The Entropy of your Password is: ";
		var entropyCombined = entropyString.concat(entropy).concat(" \n          The higher this value, the better!");
		var entropyWord = new Text(entropyCombined,"bold 16px Arial", "#FFF");
		entropyWord.x = 400; entropyWord.y = 420;
		
		stage.addChild(winText);
		stage.addChild(nutritionText);
		stage.addChild(questionText);
		stage.addChild(yesB);
		stage.addChild(noB);
		stage.addChild(entropyWord);
		
		stage.update();
  }


  function detectKey(e){
	 //alert(e.keyCode);
	 
    if(e.keyCode!=8){
      var keyID= e.charCode;
      var s= String.fromCharCode(e.charCode);
      console.log(GameController().currentIndex);
      if (
          (keyID==94)||
          ((keyID<=122)&&(keyID>=97))||
          ((keyID<=90)&&(keyID>=33))
        ){
          if ((keyID!=45)&&(keyID!=43)&&(keyID!=39)&&(keyID!=34)&&(keyID!=61))
          {
            if (patty_stack.length<=8)
            {
	            if (GameController().passwordCreated)
	            {
	            	//password already created
		            var input = String.fromCharCode(e.charCode);
		            
		            if (input == word_stack[GameController().currentIndex].text)
		            {
		            	// add a patty
		            	addPatty(keyID);
		            	speech.text = "Cool. Keep Goin'!";
		            	mouth.image.src= ("./img/cartman/mouths/o.png");
		            			            	
		            	//check if we have reached the end of character matching
			            if (GameController().currentIndex >= word_stack.length)
			            {
			            	//check how many times we have repeat typing password
			            	GameController().numberOfServedCustomer++;
			            	//adjust text for hint showing
			            	//showHint(GameController().numberOfServedCustomer);
			            	var remaining= numberOfMemorize-GameController().numberOfServedCustomer;
			            	speech.text = "One Down! Good Job! \n Only "+remaining+" more Kennys left!";
			            	mouth.image.src= ("./img/cartman/mouths/open.png");
			            	for (var i=0;i<hint_stack.length;i++)
			            	{
				            	hint_stack[i].alpha-=0.15;
				            	
				            }
				            hint.alpha-=0.15;

			            	if (GameController().numberOfServedCustomer < numberOfMemorize)
			            	{
				            	memorizeReset();
				            	updateKenny();
			            	}
			            	if (GameController().numberOfServedCustomer == numberOfMemorize)
			            	{
			            		updateKenny();
				            	showCompleteScreen();
			            	}
				            
				        }
					}
					else
					{
						speech.text = "Wrong ingredient! Try again!";
						mouth.image.src= ("./img/cartman/mouths/bigO.png");
				    }
				 }
				 else
				 {
					 // first time create password
					 addPatty(keyID);
					 sizeUpEric();
				 }
            }
            	
          }
      }
    }
  }

};

